import * as React from 'react'
import Button from 'antd/lib/button/button'
import Card from 'antd/lib/card'
import Checkbox from 'antd/lib/checkbox/Checkbox'
import Input from 'antd/lib/input/Input'
import { Col } from 'antd/lib/grid'

export interface ToShowInterface {
  text: string
  isEditing: boolean
  isComplete: boolean
}
export interface ListItemEvents {
  onClickDelButton: (index: number) => void
  switchListItemEditStatus: (index: number, status: boolean) => void
  onClickSaveButton: (index: number, value: string) => void
  switchListItemCompleteStatus: (index: number, e: React.ChangeEvent<HTMLInputElement>) => void
}
export interface ListItemProps extends ListItemEvents {
  todo: ToShowInterface
  index: number
}

interface ListItemStates {
  value: string
}

export default class ListItem extends React.Component<ListItemProps, ListItemStates> {
  constructor(props: ListItemProps) {
    super(props)
    this.state = {
      value: '',
    }
  }
  onClickSaveButton = () => {
    this.props.onClickSaveButton(this.props.index - 1, this.state.value)
  }

  onInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({
      value: e.currentTarget.value,
    })
  }
  render() {
    const indexJSX = (
      <Col span={2} offset={1}>
        <Checkbox checked={this.props.todo.isComplete} onChange={e => this.props.switchListItemCompleteStatus(this.props.index - 1, e)} />
        {this.props.index}
      </Col>
    )
    const currentView = this.props.todo.isEditing ? (
      <div>
        {indexJSX}
        <Col span={14} offset={1}>
          <Input defaultValue={this.props.todo.text} onPressEnter={this.onClickSaveButton} onChange={this.onInputChange} />
        </Col>
        <Col span={2} offset={1}>
          <Button type="danger" onClick={this.onClickSaveButton}>
            保存
          </Button>
        </Col>
        <Col span={2} offset={1}>
          <Button type="primary" onClick={() => this.props.switchListItemEditStatus(this.props.index - 1, false)}>
            取消
          </Button>
        </Col>
      </div>
    ) : (
      <div>
        {indexJSX}
        <Col span={14} offset={1}>
          {this.props.todo.text}
        </Col>
        <Col span={2} offset={1}>
          <Button type="primary" onClick={e => this.props.switchListItemEditStatus(this.props.index - 1, true)}>
            修改
          </Button>
        </Col>
        <Col span={2} offset={1}>
          <Button type="danger" onClick={e => this.props.onClickDelButton(this.props.index - 1)}>
            删除
          </Button>
        </Col>
      </div>
    )
    return <Card>{currentView}</Card>
  }
}
